﻿using System;
using System.ComponentModel.Composition;
using System.Web;
using Glimpse.Core.Extensibility;
using Glimpse.Elmah.Infrastructure;
using Newtonsoft.Json;

namespace Glimpse.Elmah.Responder
{
    [GlimpseHandler]
    public class ElmahHandler : IGlimpseHandler
    {
    	private readonly IRepository _repository;

        [ImportingConstructor]
    	public ElmahHandler() 
			: this(new ErrorRepository())
    	{
    	}

		public ElmahHandler(IRepository repository)
		{
			if (repository == null)
				throw new ArgumentNullException("repository");

			_repository = repository;
		}

    	public string ResourceName
        {
            get { return "Elmah"; }
        }

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContextBase contextBase)
        {
            if (contextBase == null)
				return;

            var pageIndex = Convert.ToInt32(contextBase.Request.QueryString["pageIndex"]);
            var pageSize = Convert.ToInt32(contextBase.Request.QueryString["pageSize"]);
            var errorPage = _repository.GetErrorPage(contextBase, pageIndex, pageSize);
			if (errorPage == null)
				return;

            var data = errorPage.GetData(contextBase);
            var dataString = JsonConvert.SerializeObject(data, Formatting.None);
            var response = contextBase.Response;
            response.AddHeader("Content-Type", "application/json");
            response.Write(dataString);
        }
    }
}